<template>
  <div class="departments">
    <el-card>
      <template #header> <div>组织架构</div> </template>

      <div style="width: 80%; margin: 0 auto">
        <tree-item :item="topInfo" style="width: 100%" @getData="getTreeData" />
        <hr>

        <el-tree
          :data="treeData"
          :props="{ label: 'name', children: 'children' }"
        >
          <template v-slot="{ data }">
            <tree-item
              :item="data"
              style="width: 100%"
              @getData="getTreeData"
            />
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 添加的小弹框 -->
    <add :init-tree-data="initTreeData" @getData="getTreeData" />
  </div>
</template>

<script>
import { companyDepartment } from '@/api/department'
import treeItem from './components/treeItem.vue'
import add from './components/add.vue'
export default {
  components: { treeItem, add },
  data() {
    return {
      initTreeData: [],
      treeData: [],
      topInfo: {
        name: '江苏传智',
        manager: '负责人',
        id: '',
        top: true
      }
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    async getTreeData() {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      // 存储原始数据
      this.initTreeData = res.data.depts
      this.treeData = this.changeData(res.data.depts)
    },
    changeData(arr, str = '') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 20px;
}
</style>
